<template>
  <div>
    <div id="search">
      <el-form :inline="true" :model="ScoreSearch" class="demo-form-inline">
        <el-form-item label="学生姓名">
          <el-input v-model="ScoreSearch.studentName" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button type="primary" size="mini" icon=el-icon-circle-plus-outline @click="showAddScore">添加</el-button>
      <el-button icon="el-icon-delete" type="danger" plain size="mini"
                 :disabled="this.multipleSelection.length>0?false:true" @click="deleteAll">删除
      </el-button>
    </div>
    <div id="role-table">
      <el-table
          :header-cell-style="{background:'rgb(242, 242, 242)'}"
          style="width: 100%;
          text-align: center"
          :data="tableData"
          :row-style="{height: '50px'}"
          :cell-style="{padding: '0'}"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
        ></el-table-column>
        <el-table-column label="班级">
          <template slot-scope="scope">
            <span>{{ scope.row.clazz }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <span>{{ scope.row.studentName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成绩">
          <template slot-scope="scope">
            <span>{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学号">
          <template slot-scope="scope">
            <span>{{ scope.row.studentNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="录入时间">
          <template slot-scope="scope">
            <span>{{ scope.row.examTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">
            </el-button>
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row.id)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="nav-page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :current-page="ScoreSearch.page"
          :page-size="ScoreSearch.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--添加 编辑课程信息弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="addScoreFormVisible" width="30%" @close="clearInfo">
      <el-form :model="ScoreForm" ref="ScoreForm" :rules="ScoreRules" label-width="90px" size="medium">
        <el-form-item label="班级" v-if="show">
          <el-input v-model="ScoreForm.clazz" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" v-if="show">
          <el-input v-model="ScoreForm.studentName" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-select clearable filterable v-model="ScoreForm.studentNo" placeholder="请选择学号">
            <el-option
                v-for="item in StudentLsit"
                :label="item.studentNo"
                :value="item.studentNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input v-model="ScoreForm.score" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="examTime">
          <el-date-picker
              v-model="ScoreForm.examTime"
              type="date"
              placeholder="选择创建时间"
              value-format="yyyy-MM-dd">
          </el-date-picker>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('ScoreForm')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import instance from "@/request/request";

export default {
  data() {
    return {
      tableData: [],
      pageSizes: [3, 5, 10, 15],
      total: 0,
      addScoreFormVisible: false,
      dialogTitle: '',
      ScoreForm: {},
      ScoreSearch: {  // 搜索数据
        page: 1,
        limit: 5
      },
      ScoreRules: {
        clazz: [{required: true, message: '请输入班级', trigger: 'blur'}],
        score: [{required: true, message: '请输入成绩', trigger: 'blur'}],
        studentName: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        examTime: [{type:'string',required: true, message: '请选择开班日期', trigger: 'change'}],
      },
      multipleSelection: [],
      //学生信息
      StudentLsit: [],
      //控制班级，姓名显示
      show: false,
    }
  },
  created() {
    this.getscoreList()
    this.getStudentNo()
  },
  methods: {
    //获取学生的学号信息
    getStudentNo() {
      instance.get("/student/getstudentNo").then(res => {
        if (res.code == 200) {
          this.StudentLsit = res.data
          return
        }
        this.$message.error(res.msg)
      }).catch(erro => {
        this.$message.error("请求失败！")
      })
    },
    //获取成绩信息
    getscoreList() {
      instance.get("/score/getlist", {params: this.ScoreSearch}).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.score
          this.total = res.data.total
          return
        }
        this.$message.error(res.msg)
      }).catch(erro => {
        this.$message.error("请求失败！")
      })
    },
    // 编辑角色
    handleEdit(index, row) {
      this.dialogTitle = "编辑成绩"
      this.addScoreFormVisible = true
      var course = Object.assign({}, row)
      this.ScoreForm = course
    },
    //更新和添加用户信息
    submit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          instance.post("/score/addOrupdate", this.ScoreForm).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.addScoreFormVisible = false
              this.getscoreList()
              this.clearInfo()
              return
            }
            this.$message.warning(res.msg)
          }).catch(erro => {
            this.$message.error("请求失败")
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //批量删除
    deleteAll() {
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        instance.delete("/score/delete/", {data: this.multipleSelection}).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.getscoreList()
            return
          }
          this.$message.warning(res.msg)
        }).catch(erro => {
          this.$message.error("请求失败！")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    // 删除角色
    handleDelete(id) {
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = [id]
        instance.delete("/score/delete/", {data: ids}).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.getscoreList()
            return
          }
          this.$message.warning(res.msg)
        }).catch(erro => {
          this.$message.error("请求失败！")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    // 搜索角色
    onSearchSubmit() {
      this.ScoreSearch.page = 1
      this.ScoreSearch.limit = 5
      this.getscoreList()
    },
    // 改变每页显示的条数触发
    handleSizeChange(val) {
      this.ScoreSearch.limit = val;
      this.getscoreList()
    },
    // 改变页码触发
    handleCurrentChange(val) {
      this.ScoreSearch.page = val;
      this.getscoreList()
    },
    // 显示弹出等
    showAddScore() {
      this.dialogTitle = "添加课程"
      this.addScoreFormVisible = true
      this.ScoreForm = {}
    },
    //清空校验规则
    clearInfo() {
      this.$refs.ScoreForm.clearValidate()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(s => s.id)
    }
  },
  watch: {
    'ScoreForm.studentNo': {
      // handler是固定的配置选项，不能改变它的名称
      handler: function (newName, oldName) {
        if (newName == undefined) {
          this.show = false
        } else {
          for (let i = 0; i < this.StudentLsit.length; i++) {
            if (this.StudentLsit[i].studentNo == newName) {
              this.ScoreForm.clazz = this.StudentLsit[i].clazz
              this.ScoreForm.studentName = this.StudentLsit[i].name
              this.show = true
            }
          }
        }
      },
      deep: true//显式的改为true，表示要进行深度监听
    }
  }
}
</script>

<style scoped>
#search {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #eee;
}

#search, #header-bth, #nav-page {
  margin: 15px;
}

#role-table {
  width: 100%;
}
</style>
